//
//  MsgSubRXTestCtr.swift
//  sinaDemo
//
//  Created by Xueming on 2021/4/25.
//

import UIKit
import RxSwift
import RxCocoa
class MsgSubRXTestCtr: UIViewController {
    //DisposeBag本身并没有所谓的"清除"功能，DisposeBag仅仅是在deinit()中调用了Disposable协议的dispose()方法，该方法是由遵守该协议的类自行实现的。
    let disposeBag = DisposeBag()
    var hold:Bool = true
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let arr:[UIColor] = [.red,.blue,.purple,.green,.brown,.darkGray,.orange,.systemPink,.cyan,.gray,.black]
        let backColor:UIColor = arr[ Int(arc4random() % 11)]
        view.backgroundColor = backColor
        
        setUpUI()
    }
    private func setUpUI(){
        //创建文本标签
        let label = UILabel(frame:CGRect(x:100, y:20, width:120, height:20))
        label.textColor = .white
        label.text = "MsgSubRXTestCtr"
        self.view.addSubview(label)
        
        //创建一个计时器（每1秒发送一个索引数）这个timer不用担心循环引用
        let timer = Observable<Int>.interval(RxTimeInterval.seconds(Int(1)), scheduler: MainScheduler.instance)
        
        
        //将已过去的时间格式化成想要的字符串，并绑定到label上
        timer.map{
            print("\($0)")
            return String(format: "%0.2d:%0.2d.%0.1d",
                          arguments: [($0 / 600) % 600, ($0 % 600 ) / 10, $0 % 10])
            
        }
            .bind(to: label.rx.text)
            .disposed(by: disposeBag)
        
        let btn:UIButton = UIButton.init(frame: CGRect(x: 20, y:  20, width: 50, height: 20))
        btn.backgroundColor = .orange
        btn.setTitle("rx btn", for: .normal)
        btn.setTitleColor(.black, for: .normal)
        view.addSubview(btn)
        btn.rx.controlEvent(.touchUpInside).subscribe(onNext:  {[unowned self] in
            print("touchUp")
            //这里会造成循环引用
            self.hold = false
        }).disposed(by: self.disposeBag)
        
        //创建文本输入框
        let textField = UITextField(frame: CGRect(x:20, y:btn
                                                    .bottom + 10, width:200, height:30))
        textField.borderStyle = .roundedRect
        self.view.addSubview(textField)
        
        //当文本框内容改变时，将内容输出到控制台上
        textField.rx.text.orEmpty.asObservable()
            .subscribe(onNext: {
                print("您输入的是：\($0)")
            })
            .disposed(by: disposeBag)
        //textField输入绑定到btn的title上
//        textField.rx.text.bind(to: btn.rx.title()).disposed(by: disposeBag)
    }
    deinit {
        print("MsgSubRXTestCtr deinit")
    }
}
